package ldkxingzhe.ldkxingzhedemo.loader;

import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import ldkxingzhe.ldkxingzhedemo.R;
import ldkxingzhe.ldkxingzhedemo.utils.LogDemo;

/**
 * Created by liangdengke on 2015/9/9.
 */
public class ContactsEntityActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {

    private final String TAG = ContactsEntityActivity.class.getSimpleName();

    private SimpleCursorAdapter mAdapter;
    private Uri mUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_loader);
        ListView listView = (ListView)findViewById(android.R.id.list);
        TextView textView = new TextView(this);
        textView.setText("没有数据");
        listView.setEmptyView(textView);

        mAdapter = new SimpleCursorAdapter(this,
                R.layout.listview_simple_contat,
                null,
                new String[]{ContactsContract.Contacts.Entity.RAW_CONTACT_ID,ContactsContract.Contacts.Entity.DATA1},
                new int[]{R.id.name,R.id.phone},
                0);
        listView.setAdapter(mAdapter);
        getLoaderManager().initLoader(0,null,this);
    }


    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        mUri = ContactsContract.Contacts.CONTENT_URI;
        mUri = Uri.withAppendedPath(mUri,"25");
        mUri = Uri.withAppendedPath(mUri,ContactsContract.Contacts.Entity.CONTENT_DIRECTORY);

        String[] projection = {
                ContactsContract.Contacts.Entity._ID,
                ContactsContract.Contacts.Entity.RAW_CONTACT_ID,
                ContactsContract.Contacts.Entity.DATA1,
                ContactsContract.Contacts.Entity.MIMETYPE,
                ContactsContract.Contacts.Entity.DISPLAY_NAME
        };

        String sortOrder =ContactsContract.Contacts.Entity.RAW_CONTACT_ID + " ASC";

        return new CursorLoader(this,mUri,projection,null,null,sortOrder);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        LogDemo.v(TAG,"onLoadFinished");
        mAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        LogDemo.v(TAG,"onLoaderReset");
        mAdapter.swapCursor(null);
    }


}
